package com.xiaobaibai.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiaobaibai.bo.BargainDelayItem;
import com.xiaobaibai.common.BargainCommon;
import com.xiaobaibai.entity.*;
import com.xiaobaibai.response.ResponseFormat;
import com.xiaobaibai.service.*;
import com.xiaobaibai.threadPool.MyThreadPoolUnit;
import com.xiaobaibai.units.BargainDelayQueueUnit;
import com.xiaobaibai.units.SecurityUnit;
import com.xiaobaibai.vo.BargainRecordingVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@Api(tags = "砍价设置接口")
@RequestMapping("/bargain")
@Slf4j
@CrossOrigin
public class BargainController {

    @Autowired
    private IBargainProductService bargainProductService;

    @Autowired
    private IBargainUserService bargainUserService;

    @Autowired
    private IBargainRecordingService bargainRecordingService;

    @Autowired
    private IProductService productService;

    @Autowired
    private BargainDelayQueueUnit bargainDelayQueueUnit;

    @Autowired
    private MyThreadPoolUnit myThreadPoolUnit;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/list")
    @ApiOperation("获取当前可砍价的商品")
    public ResponseFormat getBargainList(){

        //1.查询用户是否有了砍价商品,如果有了就跳往自己的砍价页面
        Integer userId = SecurityUnit.getUserId();

        QueryWrapper<BargainUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("id","product_id","bargain_progress","failure_time","status");
        queryWrapper.eq("user_id",userId);
        //有正在砍价中的,或者已经砍价成功的,尚未兑换的
        queryWrapper.in("status",0,2);
        BargainUser bargainUser = bargainUserService.getOne(queryWrapper);

        if(bargainUser!=null){
            //获取自己砍价的详情信息,然后展现给用户
            //1.当前商品信息
            //2.商品进度
            //3.商品砍价记录
            //商品信息
            Integer productId = bargainUser.getProductId();
            Product product = productService.getProductById(productId);

            //砍价记录,时效性,不可缓存
            QueryWrapper<BargainRecording> q2=new QueryWrapper<>();
            q2.eq("bargain_user_id",bargainUser.getId());
            List<BargainRecording> list = bargainRecordingService.list(q2);

            Map<String,Object> map=new HashMap<>();
            map.put("product",product);
            map.put("recording",list);
            map.put("bargain",bargainUser);
            return ResponseFormat.ok("有砍价",map);
        }
        //每次申请都是24小时间隔,所以就不用另设24小时申请一次了
        List<Product> list = bargainProductService.getOkProduct();
        return ResponseFormat.ok("无砍价",list);
    }

    @GetMapping("/detail/{id}")
    @ApiOperation("查看一用户的砍价商品进度")
    public ResponseFormat bargainDeleteById(@PathVariable(value = "id")Integer id){

        QueryWrapper<BargainUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.select("id","product_id","bargain_progress","failure_time","status");
        queryWrapper.eq("id",id);
        //有正在砍价中的,或者已经砍价成功尚未兑换的
        queryWrapper.in("status",0,2);
        BargainUser bargainUser = bargainUserService.getOne(queryWrapper);
        if(bargainUser==null){
            return ResponseFormat.failure("目标用户的砍价商品已经过期");
        }
        //砍价记录,时效性,不可缓存
        QueryWrapper<BargainRecording> q2=new QueryWrapper<>();
        q2.eq("bargain_user_id",bargainUser.getId());
        List<BargainRecording> list = bargainRecordingService.list(q2);

        Integer productId = bargainUser.getProductId();
        Product product = productService.getProductById(productId);

        Map<String,Object> map=new HashMap<>();
        map.put("bargain",bargainUser);
        map.put("product",product);
        map.put("recording",list);
        return ResponseFormat.ok("有砍价",map);
    }

    @GetMapping("/recording")
    @ApiOperation("用户过往砍价商品记录")
    public ResponseFormat recording(){

        Integer userId = SecurityUnit.getUserId();
        QueryWrapper<BargainUser> q1=new QueryWrapper<>();
        q1.select("product_id","bargain_progress","status","create_time");
        q1.eq("user_id",userId);
        List<BargainUser> list = bargainUserService.list(q1);
        List<BargainRecordingVo> result=new ArrayList<>(list.size());
        list.forEach(l->{
            Product product = productService.getProductById(l.getProductId());
            BargainRecordingVo bargainRecordingVo=new BargainRecordingVo(product.getProductName(),
                    l.getBargainProgress(),l.getStatus(),l.getCreateTime());
            result.add(bargainRecordingVo);
        });
        return ResponseFormat.ok("获取记录成功",result);
    }

    @PostMapping("/pick/{productId}")
    @ApiOperation("用户选择砍价商品")
    public ResponseFormat prickProduct(@PathVariable(value = "productId")Integer productId){
        //1.查询是否此商品是否可以砍价
        //2.用户是否已经有了砍价商品

        Integer userId = SecurityUnit.getUserId();

        QueryWrapper<BargainProduct> queryWrapper=new QueryWrapper<>();
//        queryWrapper.select("id");//查询出全部,因为后面要用
        queryWrapper.eq("product_id",productId);
        BargainProduct bargainProduct = bargainProductService.getOne(queryWrapper);
        if(bargainProduct==null)
            return ResponseFormat.failure("此商品不可砍价");

        QueryWrapper<BargainUser> q2=new QueryWrapper<>();
        q2.select("id");
        q2.eq("user_id",userId);
        q2.eq("status",0);//正在砍价中
        BargainUser already = bargainUserService.getOne(q2);
        if(already!=null)
            return ResponseFormat.failure("已有正在砍价的商品");

        //通过校验,可以申请砍价商品
        BargainUser bargainUser = BargainUser.convertToBargainUser(bargainProduct, userId);
        bargainUserService.save(bargainUser);//存入mysql
        //加入redis延时队列
        BargainDelayItem bargainDelayItem=
                new BargainDelayItem(bargainUser.getId(),DateUtils.addHours(new Date(),24));
        bargainDelayQueueUnit.saveBargainDelayItem(bargainDelayItem);
        return ResponseFormat.ok("成功选择砍价商品,id:"+productId);
    }

    @PostMapping("/help/{id}")
    @ApiOperation("用户帮助一名砍价用户砍价")
    public ResponseFormat helpBargainUser(@PathVariable(value = "id")Integer id){
        //传来的是目标被帮助砍价用户的id
        //用户一天只能帮助别人3次
        Integer userId = SecurityUnit.getUserId();//怎么判断是否为新用户呢?注册时间小于24小时
        Long increment = stringRedisTemplate.opsForHash()
                .increment(BargainCommon.HelpMap, userId.toString(), 1);
        if(increment>3)//已在管理端每天凌晨清除次数map
            return ResponseFormat.failure("每天仅能帮助他人3次哦");
        boolean flag = bargainRecordingService.haveHelp(id,userId);
        if(flag)//已经帮砍
            return ResponseFormat.failure("今天你已经帮它助力了哦");
        //异步去帮忙砍价
        myThreadPoolUnit.bargainHelpUser(userId,id);
        return ResponseFormat.ok("砍价成功");
    }

    @GetMapping("/success")
    @ApiOperation("获取尚未兑换的砍价商品")
    public ResponseFormat getSuccessBargain(){
        Integer userId = SecurityUnit.getUserId();
        QueryWrapper<BargainUser> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("user_id",userId);
        queryWrapper.select("id","product_id");
        //有正在砍价中的,或者已经砍价成功的,尚未兑换的商品
        queryWrapper.eq("status",2);//尚未兑换的
        BargainUser bargainUser = bargainUserService.getOne(queryWrapper);
        if(bargainUser==null)
            return ResponseFormat.ok("无砍价成功商品");
        Product product = productService.getProductById(bargainUser.getProductId());
        Map<String,Object> map=new HashMap<>();
        map.put("product",product);
        map.put("bargain",bargainUser);
        return ResponseFormat.ok("有砍价成功商品",product);
    }

}
